import Cookies from 'js-cookie';
import {Message} from 'element-ui';
import requestConfig from '@/api/config.js';

export default class UploadAdapter {
  constructor( loader ) {
      // The file loader instance to use during the upload.
      this.loader = loader;
  }

  // Starts the upload process.
  upload() {
      return this.loader.file
          .then( file => new Promise( ( resolve, reject ) => {
              this._initRequest();
              this._initListeners( resolve, reject, file );
              this._sendRequest( file );
          } ) );
  }

  // Aborts the upload process.
  abort() {
      if ( this.xhr ) {
          this.xhr.abort();
      }
  }

  // Initializes the XMLHttpRequest object using the URL passed to the constructor.
  _initRequest() {
      let xhr = this.xhr = new XMLHttpRequest();
      this.xhr.withCredentials = true;
      let baseURL = requestConfig[process.env.NODE_ENV].api

      xhr.open( 'POST', baseURL + '/object/richtext/image/upload/', true );
      xhr.responseType = 'json';
      xhr.setRequestHeader('X-CSRFToken', Cookies.get('csrftoken'));
  }

  // Initializes XMLHttpRequest listeners.
  _initListeners( resolve, reject, file ) {
      const xhr = this.xhr;
      const loader = this.loader;
      const genericErrorText = `Couldn't upload file: ${ file.name }.`;
      if(file.size > 1024 * 1024){
          Message.warning("图片大小不可超过1M");
          return reject();
      }

      xhr.addEventListener( 'error', () => reject( genericErrorText ) );
      xhr.addEventListener( 'abort', () => reject() );
      xhr.addEventListener( 'load', () => {
          const response = xhr.response;

          if ( !response || response.error ) {
              return reject( response && response.error ? response.error.message : genericErrorText );
          }

          resolve( {
              default: response.data.attach_url
          } );
      } );

      if ( xhr.upload ) {
          xhr.upload.addEventListener( 'progress', evt => {
              if ( evt.lengthComputable ) {
                  loader.uploadTotal = evt.total;
                  loader.uploaded = evt.loaded;
              }
          } );
      }
  }

  // Prepares the data and sends the request.
  _sendRequest( file ) {
      // Prepare the form data.
      const data = new FormData();

      data.append( 'location', file );

      // Send the request.
      this.xhr.send( data );
  }
}